import {Ble} from "ble.js"
import {Protocol} from "protocol.js"
// import {Test} from "/test.js"

class Sender{

  constructor(size){
    this.arrayBuffe = new Array()
    if (size == undefined || size <= 0){
      this.bufferSize = 1
    }else{
      this.bufferSize = size
    }
    this.startAdv = false
  }

  sendData(bytes){
    if (this.arrayBuffe.length >= this.bufferSize){
      this.arrayBuffe.pop()
    }
    this.arrayBuffe.push(bytes)
    if (this.startAdv == false){
      this.startAdvertising()
    }
  }

  startAdvertising(){
    if (this.arrayBuffe.length != 0){
      this.startAdv = true
      let bytes = this.arrayBuffe.shift()
      Ble.server.startAdvertising({
        advertiseRequest: {
            serviceUuids: bytes
        },
        powerLevel: 'high',
        success: (res) => {
            console.log(" advertise message success ")
            this.timer = setTimeout(() => {
                Ble.server.stopAdvertising({})
                this.startAdvertising()
            }, 260)
        },
        fail: (error) => {
            console.log(JSON.stringify(error))
        },
        complete: () => {
            console.log(" advertise message complete ")
        }
      })
    }else{
      this.startAdv = false
      console.log("adv complete ")
    }

  }
 
}

export {Sender}